<template>
    <div class="register-container">
        <!-- 返回首页按钮 -->
        <el-button icon="ArrowLeft" circle class="home-button" @click="goToHome" />

        <el-card class="register-card" shadow="hover">
            <h2>欢迎注册</h2>

            <el-form :model="form" :rules="rules" ref="formRef" label-position="left" label-width="80px"
                @submit.prevent="submitRegister">
                <!-- 用户名 -->
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名" />
                </el-form-item>

                <!-- 邮箱 -->
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>

                <!-- 密码 -->
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" placeholder="请输入密码" type="password" show-password />
                </el-form-item>

                <!-- 验证码 -->
                <el-form-item label="验证码" prop="code">
                    <el-input v-model="form.code" placeholder="请输入验证码" style="width: 60%" />
                    <el-button type="primary" plain style="margin-left: 10px" :disabled="!!countdown"
                        @click="sendEmailCode">
                        {{ countdown ? `${countdown}s后重发` : '获取验证码' }}
                    </el-button>
                </el-form-item>

                <!-- 注册按钮 -->
                <el-button native-type="submit" type="primary" class="submit-btn" :loading="loading">
                    注册
                </el-button>

                <!-- 登录提示 -->
                <div class="login-tip">
                    已有账号？
                    <span @click="goToLogin">立即登录</span>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as userApi from '@/api/login';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const loading = ref(false);
const formRef = ref(null);
const countdown = ref(0);

// 表单数据（不再包含 avatarUrl）
const form = reactive({
    username: '',
    email: '',
    password: '',
    code: ''
});

// 校验规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度为 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 32, message: '密码长度应在 6 到 32 个字符之间', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { pattern: /^\d{6}$/, message: '验证码必须为 6 位数字', trigger: 'blur' }
    ]
};

// 发送邮箱验证码
const sendEmailCode = async () => {
    if (!form.email) {
        ElMessage.error('请先输入邮箱');
        return;
    }

    // ✅ 安全检查：formRef 是否存在
    if (!formRef.value) {
        ElMessage.error('表单未初始化，请稍后重试');
        return;
    }

    try {
        await formRef.value.validateField('email');
    } catch {
        return; // 校验失败
    }

    if (countdown.value > 0) return;

    try {
        const res = await userApi.sendEmailCode(form.email);
        if (res.success) {
            ElMessage.success('验证码已发送');
            startCountdown(60);
        } else {
            ElMessage.error(res.message || '发送失败');
        }
    } catch (err) {
        console.error('发送验证码失败:', err);
        ElMessage.error('发送失败，请检查网络');
    }
};

// 倒计时
const startCountdown = (seconds) => {
    countdown.value = seconds;
    const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
            clearInterval(timer);
        }
    }, 1000);
};

// 提交注册
const submitRegister = async () => {
    // ✅ 安全检查
    if (!formRef.value) {
        ElMessage.error('表单未准备好');
        return;
    }

    try {
        await formRef.value.validate(async (valid) => {
            if (!valid) {
                ElMessage.error('请检查表单填写');
                return;
            }

            loading.value = true;
            try {
                // ✅ 提交时不包含未使用的字段
                const res = await userApi.register({
                    username: form.username,
                    email: form.email,
                    password: form.password,
                    code: form.code
                });

                if (res.success) {
                    ElMessage.success('注册成功，请登录');
                    router.push('/login');
                } else {
                    ElMessage.error(res.message || '注册失败');
                }
            } catch (err) {
                console.error('注册请求失败:', err);
                ElMessage.error('注册失败，请检查网络');
            }
        });
    } catch (err) {
        console.error('表单验证异常:', err);
    } finally {
        loading.value = false;
    }
};

// 页面跳转
const goToLogin = () => {
    router.push('/auth/login');
};

const goToHome = () => {
    router.push('/home');
};

// 组件挂载完成（可选，用于调试）
onMounted(() => {
    console.debug('Register page mounted');
});
</script>

<style lang="scss" scoped>
.register-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    position: relative;

    .home-button {
        position: absolute;
        top: 20px;
        left: 20px;
        z-index: 10;
        background-color: white;
        border: 1px solid #ddd;
        color: #333;

        &:hover {
            background-color: #f0f0f0;
        }
    }

    .register-card {
        width: 100%;
        max-width: 460px;
        padding: 2.5rem;
        border-radius: 12px;
        background-color: #ffffffee;
        backdrop-filter: blur(10px);

        h2 {
            margin-bottom: 1.8rem;
            font-weight: 600;
            color: #333;
            text-align: center;
        }

        .submit-btn {
            width: 100%;
            margin-top: 1rem;
        }

        .login-tip {
            margin-top: 1rem;
            font-size: 0.9rem;
            color: #666;
            text-align: center;

            span {
                color: #4f8cf2;
                cursor: pointer;
                margin-left: 4px;

                &:hover {
                    text-decoration: underline;
                }
            }
        }
    }
}
</style>